// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import * as common from "x.common";
import * as host from "x.host";
import { registry, XPlugin, XPluginHost } from "x.host";
import project from "./project";

type PluginConfig =
    | string[]
    | {
          uri: string[];
      };

export class XWeb extends XPluginHost {
    constructor() {
        super("x.web/host", project.version, project.name);
    }

    load(configs: PluginConfig[]) {
        let loading = 0;
        configs.forEach((p) => {
            let uri = [];

            if (p instanceof Array) {
                uri = p;
            } else {
                uri = p.uri;
            }

            uri.forEach((src) => {
                loading++;
                let script = document.createElement("script");
                script.onload =
                    script.onabort =
                    script.onerror =
                        () => {
                            loading--;
                            if (loading <= 0) {
                                this.emit("load");
                            }
                        };
                script.type = "module";
                script.src = src;
                document.querySelector("head")?.appendChild(script);
            });
        });
    }
}

const global = window as any;
global.x = {
    host: host,
    common: common,
};
global.vue = common.vue;

const xWeb = new XWeb();
registry.on("plugin-add", (plugin: XPlugin) => {
    host.Log.info(`plugin-add ` + plugin.name);
    xWeb.pluginAdd(plugin);
});

fetch("plugins.json")
    .then((resp) => resp.json())
    .then(xWeb.load.bind(xWeb));

export { xWeb };
